package controller;

import java.io.IOException;
import java.sql.SQLException;

import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import domain.Alternative;
import domain.Project;

/**
 * Servlet implementation class AlternativeController
 */
public class AlternativeController extends HttpServlet {
	private static final long serialVersionUID = 1L;
       
    /**
     * @see HttpServlet#HttpServlet()
     */
    public AlternativeController() {
        super();
        // TODO Auto-generated constructor stub
    }

	/**
	 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		// TODO Auto-generated method stub
	}

	/**
	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		// TODO Auto-generated method stub
		String requestUri = request.getRequestURI();
		if (requestUri != null && requestUri.endsWith("/alternative")){
			String alternativeName = request.getParameter("alternativeName");
			String projectId = request.getParameter("projectId");
			String message = "";
			Alternative alternative = new Alternative();
				alternative.setName(alternativeName);
			Project project = new Project();
			
			try {
				project = Project.find(Long.parseLong(projectId));
				project.newAlternative(alternative);
				project.findCriterias();
				project.findAlternatives();
				message = "Alternative was successfully created!!";
				request.setAttribute("message", message);
				request.setAttribute("project", project);
				RequestDispatcher dispatcher = getServletContext().getRequestDispatcher("/project.jsp");
				dispatcher.forward(request,response);
			} catch (SQLException e) {
				// TODO Auto-generated catch block
				message = "Some problem occurs!!";
				e.printStackTrace();
				request.setAttribute("message", message);
				request.setAttribute("project", project);
				RequestDispatcher dispatcher = getServletContext().getRequestDispatcher("/project.jsp");
				dispatcher.forward(request,response);
			}
		}
	}

}
